<script>
import {
  BREAKPOINTS,
  defaultBatchConfig,
  defaultEmptyConfig,
  defaultLayoutConfig,
  defaultPageConfig,
  defaultQueryConfig,
  defaultTableConfig,
  formAttributes,
  tableAttributes,
  tableEvents,
  REF_QUERY_FORM,
  REF_BATCHBAR_C,
  REF_PAGEBAR_C,
  REF_QUERY_FORM_C,
  REF_QUERY_TABLE,
  REF_QUERY_TABLE_TWO,
  REF_TOOLBAR_C,
  defaultToolConfig
} from "@/components/QueryTableRender/config";
import elementResizeDetectorMaker from "element-resize-detector";
import Pagination from "@/components/Pagination";
import TableTool from "@/components/QueryTableRender/TableTool";
import {
  debounce,
  getPropsData,
  mergeOptions,
  transformSubmitValue
} from "@/components/QueryTableRender/utils";
import {
  generateColumnScopedDefault,
  generateColumnScopedDefaultTwo,
  generateToolbarNode,
  generateSubmitterNode,
  generatePaginationNode,
  generatePaginationTwoNode,
  generateBatchBarNode,
  generateBatchFooterNode
} from "@/components/QueryTableRender/generate";

export default {
  name: "QueryTableRender",
  components: { Pagination, TableTool },
  props: {
    tableCount: { // 几个表格
      type: Number,
      default: 1
    },
    queryModel: {
      type: Object,
      // required: true,
      default: () => ({})
    },
    transformQuery: {
      type: Function,
      default: undefined,
      validator: function(value) {
        // 必须是一个方法
        return typeof value === "function";
      }
    },
    tableColumn: {
      type: Array,
      required: true,
      default: () => []
    },
    tableTwoColumn: { // 第二个列表
      type: Array,
      required: false,
      default: () => []
    },
    tableTwoPage: { // 第二个表是否要分页
      type: Boolean,
      default: false,
    },
    custPageTwoSize: { // 自定义第二张表一页多少条
      type: Number,
      default: 10,
    },
    custPageSize: { // 自定义一页多少条
      type: Number,
      default: 10,
    },
    rowKey: {
      type: String,
      default: "id"
    },
    excessHeight: { // 多余高度，需要减去
      type: Number,
      default: 0
    },
    /**
     * @name 表单结束后调用
     * @description 支持异步操作
     *
     * @example request={async (values) => { await save(values); return true }}
     */
    tableRequest: {
      type: Function,
      default: () => ({}),
      // required: true,
      validator: function(value) {
        // 这个值必须是一个方法
        return typeof value === "function";
      }
    },
    tableTwoRequest: {
      type: Function,
      default: () => ({}),
      // required: true,
      validator: function(value) {
        // 这个值必须是一个方法
        return typeof value === "function";
      }
    },
    toolbarRender: {
      type: Function,
      default: undefined,
      validator: function(value) {
        // 必须是一个方法
        return typeof value === "function";
      }
    },
    titleRender: {
      type: Function,
      default: undefined,
      validator: function(value) {
        // 必须是一个方法
        return typeof value === "function";
      }
    },
    titleTwoRender: {
      type: Function,
      default: undefined,
      validator: function(value) {
        // 必须是一个方法
        return typeof value === "function";
      }
    },
    batchBarRender: {
      type: Function,
      default: undefined,
      validator: function(value) {
        // 必须是一个方法
        return typeof value === "function";
      }
    },
    batchFooterRender: {
      type: Function,
      default: undefined,
      validator: function(value) {
        // 必须是一个方法
        return typeof value === "function";
      }
    },
    batchHandler: {
      type: Function,
      default: undefined,
      validator: function(value) {
        // 必须是一个方法
        return typeof value === "function";
      }
    },
    resetFormModel: {
      type: Function,
      default: undefined,
      validator: function(value) {
        // 必须是一个方法
        return typeof value === "function";
      }
    },
    // rowKey: {
    //   type: Function,
    //   default: undefined,
    //   validator: function(value) {
    //     // 必须是一个方法
    //     return typeof value === "function";
    //   }
    // },
    layoutConfig: {
      type: Object,
      default: () => ({})
    },
    queryConfig: {
      type: Object,
      default: () => ({})
    },
    tableConfig: {
      type: Object,
      default: () => ({})
    },
    pageConfig: {
      type: Object,
      default: () => ({})
    },
    batchConfig: {
      type: Object,
      default: () => ({})
    },
    toolConfig: {
      type: Object,
      default: () => ({})
    },
    emptyConfig: {
      type: Object,
      default: () => ({})
    },
    tableData:{
      type: Array,
      default: () => ([])
    },
    tableTwoData: {
      type: Array,
      default: () => ([])
    },
    tableTwoTabs: {
      type: Array,
      default: () => ([])
    },
    selectedTab: {
      type: String,
      default: ''
    },
    showSummary: { // 是否显示合计行
      type: Boolean,
      default: false
    },
    getSummaryFunc: { // 合计行方法
      type: Function,
      default: undefined,
      validator: function(value) {
        // 必须是一个方法
        return typeof value === "function";
      }
    },
    showTableBatchView: { // 是否显示批量视图
      type: Boolean,
      default: true,
    },
    showSummaryTwo: { // 是否显示合计行 第二张表
      type: Boolean,
      default: false
    },
    getSummaryTwoFunc: { // 合计行方法
      type: Function,
      default: undefined,
      validator: function(value) {
        // 必须是一个方法
        return typeof value === "function";
      }
    },
    // :table-two-tabs
  },
  data() {
    return {
      width: 0,
      height: 0,
      tableColumnLocal: [],
      tableTwoColumnLocal: [],
      searchMode: false,
      // 查询表单
      spanConfig: { span: 3, layout: "right" },
      collapse: true,
      hideCollapse: false,
      spanHideIndex: 0,
      qyLoading: false,
      queryModelDefault: this.queryModel,
      queryParams: {},
      // 列表
      tbLoading: false,
      tableDataLocal: [], // 第一个表格的数据
      tableTwoDataLocal: [], // 第二个表格的数据
      tableTwoTabsLocal: [], // 第二个表个的tabs
      tableSize: "",
      calcTableHeight: 0,
      // 列表批量操作
      curSelectionPage: 1,
      allSelectionCache: {},
      batchLoading: false,

      radioInputValue: undefined, // 值

      // 分页
      pageParams: {
        pageNum: 1,
        pageSize: 10
      },
      pageTotal: 0,

      // 分页第二张表
      pageParamsTwo: {
        pageNum: 1,
        pageSize: 10,
        pageSizes: [10, 20, 30, 50]
      },
      pageTotalTwo: 0,

      // 配置
      _layoutConfig: {},
      _queryConfig: {},
      _tableConfig: {},
      _pageConfig: {},
      _batchConfig: {},
      _toolConfig: {},
      _emptyConfig: {},
      $formAttrs: {},
      $tableAttrs: {},
      $tableListeners: {},
      fixBottomPadding: defaultLayoutConfig.padding[2]
    };
  },
  computed: {
    tableHeight() {
      // (this.tableCount == 2? '' : this.calcTableHeight),
      if (this.tableCount != 2 && this.custPageSize == 10) {
        return this.calcTableHeight;
      }
      // return undefined;
      this.$nextTick(() => {
        // this.onResize();
        // this.$refs[REF_QUERY_TABLE]?.doLayout();
        this.$refs[REF_QUERY_TABLE_TWO]?.doLayout();
      });
    },
    showQueryForm() {
      return !!this.$slots.form;
    },
    showTableToolbar() {
      return this.toolbarRender || this.titleRender || this._tableConfig.showConfig;
    },
    showTableBatch() {
      return !this._batchConfig.hideBatch && this.allSelections.length;
    },
    showPageBar() {
      return !this._pageConfig.hidePage && !this._tableConfig.isTree;
    },
    tableEmpty() {
      return this.searchMode
        ? {
            emptyImg: this._emptyConfig.emptySearch,
            emptyText: this._emptyConfig.emptySearchText
          }
        : {
            emptyImg: this._emptyConfig.emptyDefault,
            emptyText: this._emptyConfig.emptyDefaultText
          };
    },
    allSelections() {
      let temp = [];
      for (const argumentsKey in this.allSelectionCache) {
        if (
          this.allSelectionCache[argumentsKey] &&
          this.allSelectionCache[argumentsKey].length
        ) {
          temp.push(...this.allSelectionCache[argumentsKey]);
        }
      }
      return temp;
    }
  },
  created() {
    this._layoutConfig = mergeOptions(defaultLayoutConfig, this.layoutConfig);
    this._queryConfig = mergeOptions(defaultQueryConfig, this.queryConfig);
    this._tableConfig = mergeOptions(defaultTableConfig, this.tableConfig);

    if (this.custPageTwoSize == 5) {
      this.pageParamsTwo.pageSize = 5;
      this.pageParamsTwo.pageSizes = [5, 10, 20, 50];
    }

    if (this.tableTwoTabs && this.tableTwoTabs.length > 0) {
      this.radioInputValue = this.tableTwoTabs[0];
    }

    // console.log('custPageSize=', this.custPageSize);
    if (this.tableCount == 2 || this.custPageSize == 5) {
      this.pageParams.pageSize = 5;
      const defaultPageConfig = {
        hidePage: false,
        startPage: 1,
        pageSizes: [5, 10, 20, 50, 100],
      }
      this._pageConfig = mergeOptions(defaultPageConfig, this.pageConfig);
    } else {
      this._pageConfig = mergeOptions(defaultPageConfig, this.pageConfig);
    }
    this._batchConfig = mergeOptions(defaultBatchConfig, this.batchConfig);
    this._toolConfig = mergeOptions(defaultToolConfig, this.toolConfig);
    this._emptyConfig = mergeOptions(defaultEmptyConfig, this.emptyConfig);
    // 初始化
    this.curSelectionPage = this.pageParams.pageNum = this._pageConfig.startPage;
    this.collapse = this._queryConfig.collapse;
    this.$formAttrs = getPropsData(this.$attrs, formAttributes);
    this.$tableAttrs = getPropsData(this.$attrs, tableAttributes);
    this.$tableListeners = getPropsData(this.$listeners, tableEvents);
    // console.log('this.$tableListeners=', this.$tableListeners);

    // 批量操作footerbar高度问题，需保存底部padding值
    this.fixBottomPadding = this._layoutConfig.padding[2];
  },
  mounted() {
    const erd = elementResizeDetectorMaker();
    erd.listenTo(
      this.$el,
      debounce(element => {
        // console.log('element=', element);
        this.width = element.offsetWidth; // 元素像素宽度(包含内边距(padding)和边框(border))
        this.height = element.offsetHeight; // 元素像素高度(包含内边距(padding)和边框(border))
        // console.log('height=', this.height);
        this.onResize();
      }, 160)
    );

    this.$once("hook:beforeDestroy", () => {
      erd && erd.uninstall(this.$el);
    });


    this.$nextTick(() => {
      if(this.tableData && this.tableData instanceof Array){
        this.tableDataLocal = this.tableData
      }
      if(this._tableConfig.immediately){
        this.initTableData();
      }

      if (this.tableCount == 2) { // 第二张表
        if (this.tableTwoData && this.tableTwoData instanceof Array) {
          this.tableTwoDataLocal = this.tableTwoData;
          this.tableTwoTabsLocal = this.tableTwoTabs;
        }
      }
    });

    let isInitTreeCol = false;
    this.tableColumn.forEach(async item => {
      if (
        this._tableConfig.isTree &&
        !isInitTreeCol &&
        !item.showOverflowTooltip &&
        !["expand", "index", "selection"].some(type => item.type)
      ) {
        item.className = "tree-col-class";
        isInitTreeCol = true;
      }
      if (item.request) {
        item._columnRequestOptions = await item.request();
      }
    });

    this.tableColumnLocal = this.tableColumn.map(col => {
      return { ...col };
    });
    this.tableTwoColumnLocal = this.tableTwoColumn.map(col => {
      return { ...col };
    });
  },
  watch:{
    tableData(value){
      this.tableDataLocal = value
    },
    tableTwoData(value) { // 第二张表
      // console.log('hahaha');
      this.tableTwoDataLocal = value;
    }
  },
  updated() {
    this.$nextTick(() => {
      this.$refs[REF_QUERY_TABLE_TWO]?.doLayout();
    });
  },
  methods: {
    // rootElementResize() {
    //   this.width = this.$el.clientWidth;
    //   this.height = this.$el.clientHeight;
    //   this.onResize();
    // },
    getSelectionData(){
      return this.allSelections
    },

    initTableData() {
      this.submitQuery(false);
    },

    submitQuery(isSearch = true) {
      // console.log('搜索=', isSearch);
      this.pageParams.pageNum = this._pageConfig.startPage;
      this.searchMode = isSearch;
      this.queryParams = transformSubmitValue(
        this.queryModelDefault,
        this._queryConfig.omitNil
      );
      this.$emit("search-submit", this.queryParams);
      this.getTableData();
    },

    resetQuery() {
      this.pageParams.pageNum = this._pageConfig.startPage;
      this.pageParamsTwo.pageNum = this._pageConfig.startPage;
      this.searchMode = false;
      if (this.resetFormModel && typeof this.resetFormModel === "function") {
        this.queryModelDefault = this.resetFormModel();
      }else{
        this.$refs[REF_QUERY_FORM]?.resetFields();
      }

      this.queryParams = transformSubmitValue(
        this.queryModelDefault,
        this._queryConfig.omitNil
      );
      this.$emit("search-reset", this.queryParams);
      this.getTableData(true);
    },

    onPageChange() {
      this.getTableData(true);
    },

    /**
     * 第二张表
     */
    onPageChangeTwo() {
      this.getTableTwoData();
    },

    changeCollapse() {
      this.collapse = !this.collapse;
      this.$emit("on-collapse");
      this.onResize();
    },

    onResize() {
      if (!this.showQueryForm) {
        this.updateTableHeight();
        return;
      }

      if (!this.width) return;

      const breakPoint = BREAKPOINTS.find(item => this.width < item[0]);

      this.hideCollapse = this.$slots.form.length < breakPoint[1];

      this.spanConfig = {
        span: breakPoint[1],
        layout: breakPoint[2]
      };

      if (this.collapse) {
        this.hideIndex = breakPoint[1] - 1 || 1;
      } else {
        this.hideIndex = this.$slots.form.length;
      }

      const modCount = (this.hideIndex + 1) % this.spanConfig.span;
      const needHideCount = modCount ? modCount : this.spanConfig.span;
      this.formItemNoMarginIndex = this.hideIndex - needHideCount;

      this.updateTableHeight();
    },

    /**
     * 更新table的高度
     */
    updateTableHeight() {
      this.$nextTick(() => {
        // console.log('excessHeight=', this.excessHeight);
        // height = 屏幕高度 - 顶部
        let height = document.body.clientHeight - 90 - 40 - 20 - this.excessHeight;
        // 查询条件高度
        const formHeight =
          this.showQueryForm && this.$refs[REF_QUERY_FORM_C]
            ? this.$refs[REF_QUERY_FORM_C]?.clientHeight
            : 0;
        // console.log('formHeight=', formHeight);
        // 功能列表页面
        const toolbarHeight =
          this.showTableToolbar && this.$refs[REF_TOOLBAR_C]
            ? this.$refs[REF_TOOLBAR_C]?.clientHeight + 16
            : 0;
        // console.log('toolbarHeight=', toolbarHeight);
        const batchbarHeight =
          this.showTableBatch && this.$refs[REF_BATCHBAR_C]
            ? this.$refs[REF_BATCHBAR_C]?.clientHeight + 16
            : 0;
        // console.log('batchbarHeight=', batchbarHeight);
        // 分页页面
        const paginationHeight =
          this.showPageBar && this.$refs[REF_PAGEBAR_C]
            ? this.$refs[REF_PAGEBAR_C]?.clientHeight
            : 0;
        // console.log('paginationHeight=', paginationHeight);
        // console.log('height=', this.height);
        const calcHeight =
          height - formHeight - toolbarHeight - batchbarHeight - paginationHeight -
          this._layoutConfig.gutter - 2 -
          this._layoutConfig.tablePadding[0] - this._layoutConfig.tablePadding[2] -
          this._layoutConfig.padding[0] - this._layoutConfig.padding[2];

        // debugger
        // console.log('calcHeight=', calcHeight);
        this.calcTableHeight = Math.max(
          this._tableConfig.minHeight,
          calcHeight
        );
        // console.log('calcTableHeight=', this.calcTableHeight);
      });
    },

    /**
     * 刷新数据
     */
    refreshTable() {
      this.getTableData(true);
    },

    refreshTableTwo() {
      this.pageParamsTwo.pageNum = this._pageConfig.startPage;
      this.getTableTwoData();
    },

    tableSizeChange(size) {
      // console.log('tableSizeChange');
      this._tableConfig.tableSize = size;
      // 操作栏尺寸变更
      const operatorColumn = this.tableColumnLocal.find(
        col => "operator" === col.type
      );
      if (operatorColumn) {
        operatorColumn.key = operatorColumn.type + Date.now();
      }

      this.$nextTick(() => {
        this.onResize();
        this.$refs[REF_QUERY_TABLE]?.doLayout();
        this.$refs[REF_QUERY_TABLE_TWO]?.doLayout();
      });
    },

    getQueryTableRef() {
      return this.$refs[REF_QUERY_TABLE];
    },

    tableColumnChange(tableColumn) {
      // console.log('tableColumnChange');
      this.tableColumnLocal = tableColumn;
      this.$nextTick(() => {
        // this.onResize();
        this.$refs[REF_QUERY_TABLE]?.doLayout();
        this.$refs[REF_QUERY_TABLE_TWO]?.doLayout();
      });
    },

    tableTwoColumnChange(tableColumn) {
      // console.log('tableColumnChange');
      this.tableTwoColumnLocal = tableColumn;
      this.$nextTick(() => {
        // this.onResize();
        // this.$refs[REF_QUERY_TABLE]?.doLayout();
        this.$refs[REF_QUERY_TABLE_TWO]?.doLayout();
      });
    },

    getQueryParams(extraParams = {}) {
      let finalQueryParams = this.queryParams;
      if (this.transformQuery && typeof this.transformQuery === "function") {
        finalQueryParams = this.transformQuery(this.queryParams);
      }
      return Object.assign({}, finalQueryParams, this.pageParams, extraParams)
    },
    refreshTableByExtraData(extraParams){
      this.pageParams.pageNum = this._pageConfig.startPage;
      this.pageParamsTwo.pageNum = this._pageConfig.startPage;
      this.getTableData(false, extraParams)
    },

    /**
     * 获取表格二的数据
     */
    async getTableTwoData() {
      // 没设置 tableRequest 就不执行
      if (!this.tableTwoRequest && typeof this.tableTwoRequest === "function") return;
      try {
        let params = {pageNum: this.pageParamsTwo.pageNum, pageSize: this.pageParamsTwo.pageSize};
        const { success, data, total } = await this.tableTwoRequest(params);

        if (success) {
          this.tableTwoDataLocal = data || [];
          this.pageTotalTwo = parseInt(total) || 0;
        } else {
          this.tableTwoDataLocal = [];
          this.pageTotalTwo = 0;
        }
      } catch(err) {
        this.tableTwoDataLocal = [];
        this.pageTotalTwo = 0;
      }
    },

    async getTableData(hideQueryLoading = false, extraParams = {}) {
      // 没设置 tableRequest 就不执行
      if (!this.tableRequest && typeof this.tableRequest === "function") return;
      // 防止重复提交、防止重复请求
      if (this.qyLoading || this.tbLoading) return;

      if (!hideQueryLoading) {
        this.qyLoading = true;
      }

      this.tbLoading = true;
      try {
        // let finalQueryParams = this.queryParams;
        // if (this.transformQuery && typeof this.transformQuery === "function") {
        //   finalQueryParams = this.transformQuery(this.queryParams);
        // }
        const { success, data, total } = await this.tableRequest(this.getQueryParams(extraParams));

        if (success) {
          this.tableDataLocal = data || [];
          this.pageTotal = parseInt(total) || 0;
        } else {
          this.tableDataLocal = [];
          this.pageTotal = 0;
        }

        this.qyLoading = false;
        this.tbLoading = false;
        setTimeout(() => {
          this.curSelectionPage = this.pageParams.pageNum;
          this.toggleCurPageSelection();
        }, 80);
      } catch (error) {
        this.qyLoading = false;
        this.tbLoading = false;
        this.tableDataLocal = [];
        this.pageTotal = 0;
      }
    },

    handleSelectionChange(multipleSelections) {
      // console.log('选择');
      if (this.pageParams.pageNum === this.curSelectionPage) {
        this.$set(
          this.allSelectionCache,
          this.pageParams.pageNum,
          multipleSelections
        );
        this.$emit("selection-change", this.allSelections.slice(0));
      }
    },

    /**
     * 点击行事件
     * @param {*} row 
     */
    handleRowClick(row) {
      // console.log('点击行');
      // this.$emit('row-click', row);
    },

    radioInput(value) {
      // console.log('oldValue=', this.radioInputValue,'; value===', value);
      if (this.radioInputValue !== value) {
        // console.log('不相同');
        this.pageParamsTwo.pageNum = this._pageConfig.startPage;
      }
      this.radioInputValue = value;
      this.$emit('radio-input', value);
    },

    /**
     * 设置指定行为高亮
     * @param {*} index 
     */
    handleHighlightCurrRow(row) {
      // let row = index;
      this.$nextTick(() => {
        this.$refs[REF_QUERY_TABLE]?.setCurrentRow(row);
      });
    },
    // setCurrentRow highlight-current-row

    clearSelection(needRefreshTable) {
      this.$refs[REF_QUERY_TABLE]?.clearSelection();
      this.allSelectionCache = {};
      this.$emit("selection-change", this.allSelections.slice(0));
      if (needRefreshTable) {
        this.submitQuery(false);
      }
    },

    /**
     * 获取选中的
     */
    getSelection() {
      const selectedList = this.$refs[REF_QUERY_TABLE]?.selection;
      return selectedList;
    },
    toggleCurPageSelection() {
      if (
        this.allSelectionCache[this.pageParams.pageNum] &&
        this.allSelectionCache[this.pageParams.pageNum].length
      ) {
        this.allSelectionCache[this.pageParams.pageNum].forEach(row => {
          let find = this.tableDataLocal.find(
            record => row[this.rowKey] === record[this.rowKey]
          );
          this.$refs[REF_QUERY_TABLE]?.toggleRowSelection(find);
        });
      }
    },
    updateTablePaddingHeight(height) {
      this._layoutConfig.padding[2] =
        this.fixBottomPadding + (height ? height : 0);
    }
  },
  render(h, context) {
    let queryFormNode = null;
    if (this.showQueryForm) {
      const submitterNode = generateSubmitterNode(h, this);
      const elFormItemNodes = (this.$slots.form || []).map((colNode, index) => {
        const key =
          colNode?.componentOptions?.propsData?.prop || "form-item" + index;
        return h(
          "div",
          {
            key: key,
            class: { "no-margin-bottom": index > this.formItemNoMarginIndex },
            style: {
              flex: `0 0 ${100 / this.spanConfig.span}%`,
              display: index < this.hideIndex ? "inline-block" : "none"
            }
          },
          [colNode]
        );
      });
      const elFormNode = h(
        "el-form",
        {
          ref: REF_QUERY_FORM,
          key: REF_QUERY_FORM,
          props: {
            model: this.queryModelDefault,
            size: this._queryConfig.size,
            labelPosition: this.spanConfig.layout,
            labelWidth: this._queryConfig.labelWidth + "px",
            labelSuffix: this._queryConfig.labelSuffix,
            ...this.$formAttrs
          }
        },
        [
          h(
            "div",
            {
              class: "query-con-form-row"
            },
            [...elFormItemNodes, submitterNode]
          )
        ]
      );

      queryFormNode = h(
        "div",
        {
          ref: REF_QUERY_FORM_C,
          class: "query-con-form",
          style: {
            padding: `${this._layoutConfig.queryPadding[0]}px ${this._layoutConfig.queryPadding[1]}px
                    ${this._layoutConfig.queryPadding[2]}px ${this._layoutConfig.queryPadding[3]}px`,
            marginBottom: `${this._layoutConfig.gutter}px`
          }
        },
        [elFormNode]
      );
    }

    let paginationNode = null;
    if (this.showPageBar) {
      // let titleTwoRender = this.titleTwoRender;
      paginationNode = generatePaginationNode(h, this);
    }

    let toolBarNode = null
    if(this.showTableToolbar){
      toolBarNode = generateToolbarNode(this.$createElement, this)
    }

    let batchBarNode = null;
    let batchFooterNode = null;
    if (this.showTableBatch && this.showTableBatchView) {
      batchBarNode = generateBatchBarNode(h, this);
      if (this._batchConfig.showFooterBar) {
        this.updateTablePaddingHeight(50);
        batchFooterNode = generateBatchFooterNode(h, this);
      }
    } else {
      if (this._batchConfig.showFooterBar) {
        this.updateTablePaddingHeight(0);
      }
    }

    const elTableColumn = this.tableColumnLocal.map((column, index) => {
      let scopedSlots = generateColumnScopedDefault(column, h, this);
      return h("el-table-column", {
        key: column.key,
        props: {
          ...column
        },
        scopedSlots: scopedSlots
      });
    });

    // console.log('elTableNode.height=', this.calcTableHeight);
    const elTableNode = h(
      "el-table",
      {
        ref: REF_QUERY_TABLE,
        key: REF_QUERY_TABLE,
        props: {
          data: this.tableDataLocal,
          // height: (this.tableCount == 2? '' : this.calcTableHeight),
          height: this.tableHeight,
          // maxHeight: (this.tableCount == 2? this.calcTableHeight : ''),
          'row-style': {height:'40px'},
          'show-summary': this.showSummary, // 是否显示合计行
          'summary-method': this.getSummaryFunc,
          size: this._tableConfig.tableSize,
          rowKey: this.rowKey,
          headerCellStyle: this._tableConfig.headerCellStyle,
          ...this.$tableAttrs
        },
        on: {
          "selection-change": this.handleSelectionChange,
          "row-click": this.handleRowClick,
          ...this.$tableListeners
        },
        directives: [
          {
            name: "loading",
            value: this._tableConfig.tableLoading && this.tbLoading
          }
        ],
        scopedSlots: {
          empty: props =>
            h("el-empty", {
              props: {
                description: this.tableEmpty.emptyText,
                image: this.tableEmpty.emptyImg
              }
            })
        }
      },
      elTableColumn
    );

    const queryTableNode = h(
      "div",
      {
        key: "query-con-table",
        class: "query-con-table",
        style: {
          padding: `${this._layoutConfig.tablePadding[0]}px ${this._layoutConfig.tablePadding[1]}px
                  ${this._layoutConfig.tablePadding[2]}px ${this._layoutConfig.tablePadding[3]}px`
        }
      },
      [toolBarNode, batchBarNode, elTableNode, paginationNode]
    );

    // 第二张表
    let elTabs = undefined;
    if (this.tableTwoTabsLocal && this.tableTwoTabsLocal.length > 0) {
      const elRadioButton = this.tableTwoTabsLocal.map((item, index) => {
        return h('el-radio-button', {
          props: {
            label: item
          }
        });
      });
      const elRadio = h('el-radio-group', {
        props: {
          size: 'small',
          value: this.selectedTab
        },
        on: {
          'input': this.radioInput
        }
      }, [elRadioButton]);
      elTabs = h('div', {
        style: {
          backgroundColor:'#fffff',
          marginBottom: `10px`
          }
      }, [elRadio]);
      // console.log('elRadio=', elRadio);
    }

    
    
    let queryTableTwoNode = undefined;
    let divSpaceNode = undefined;
    
    if (this.tableCount == 2) {

      let paginationNodeTwo = null;
      if (this.tableTwoPage == true) { // 是否有分页
        // 分页
        paginationNodeTwo = generatePaginationTwoNode(h, this);
      }

      // console.log('elTableTwoColumn');
      const elTableTwoColumn = this.tableTwoColumnLocal.map((column, index) => {
        let scopedSlots = generateColumnScopedDefaultTwo(column, h, this, this.tableTwoPage);
        return h("el-table-column", {
          key: column.key,
          props: {
            ...column
          },
          scopedSlots: scopedSlots
        });
      });

      const elTableTwoNode = h(
        "el-table",
        {
          ref: REF_QUERY_TABLE_TWO,
          key: REF_QUERY_TABLE_TWO,
          props: {
            data: this.tableTwoDataLocal,
            // height: (this.tableCount == 2? (this.calcTableHeight * 0.5) : this.calcTableHeight),
            'row-style': {height:'47px'},
            'show-summary': this.showSummaryTwo, // 是否显示合计行
            'summary-method': this.getSummaryTwoFunc,
            size: this._tableConfig.tableSize,
            rowKey: this.rowKey,
            headerCellStyle: this._tableConfig.headerCellStyle,
            ...this.$tableAttrs
          },
          on: {
            "selection-change": this.handleSelectionChange,
            ...this.$tableListeners
          },
          directives: [
            {
              name: "loading",
              value: this._tableConfig.tableLoading && this.tbLoading
            }
          ],
          scopedSlots: {
            empty: props =>
              h("el-empty", {
                props: {
                  description: this.tableEmpty.emptyText,
                  image: this.tableEmpty.emptyImg
                }
              })
          }
        },
        elTableTwoColumn
      );

      divSpaceNode = h('div', {style: {
        height: '20px',
        backgroundColor: '#F0F2F5'
      }})

      queryTableTwoNode = h(
        "div",
        {
          key: "query-con-table-two",
          class: "query-con-table-two",
          style: {
            backgroundColor:'#fffff',
            // padding: `${this._layoutConfig.tablePadding[0]}px ${this._layoutConfig.tablePadding[1]}px
                  // ${this._layoutConfig.tablePadding[2]}px ${this._layoutConfig.tablePadding[3]}px`
            padding: `${this._layoutConfig.tableTwoPadding[0]}px ${this._layoutConfig.tableTwoPadding[1]}px
                    ${this._layoutConfig.tableTwoPadding[2]}px ${this._layoutConfig.tableTwoPadding[3]}px`
          }
        },
        [elTabs, elTableTwoNode, paginationNodeTwo]
      );
    }
    


    return h(
      "div",
      {
        key: "query-con",
        class: "query-con",
        style: {
          padding: `${this._layoutConfig.padding[0]}px ${this._layoutConfig.padding[1]}px ${this._layoutConfig.padding[2]}px ${this._layoutConfig.padding[3]}px`
        }
      },
      [queryFormNode, queryTableNode, batchFooterNode, queryTableTwoNode, divSpaceNode]
    );
  }
};
</script>

<style lang="scss" scoped>
.query-con-table-two {
  background-color: #ffffff;
  padding: 0, 20, 20px, 20px;
}
.query-con {
  width: 100%;
  max-height: 100%;
  min-height: 90%;
  box-sizing: border-box;
  position: unset !important;
  // overflow: auto;

  scrollbar-color: #d3dce6 #99a9bf;
  scrollbar-width: thin;

  &::-webkit-scrollbar-track-piece {
    background: #d3dce6;
  }

  &::-webkit-scrollbar {
    width: 6px;
    height: 8px;
  }

  &::-webkit-scrollbar-thumb {
    background: #99a9bf;
    border-radius: 5px;
    -webkit-box-shadow: inset 0 0 3px #d3dce6;
  }

  &::-webkit-scrollbar-track {
    -webkit-box-shadow: inset 0 0 3px #99a9bf;
    border-radius: 0;
    background: #d3dce6;
  }

  & > * {
    box-sizing: border-box;
  }

  &-form {
    background: #ffffff;
    padding-top: 20px !important;
    padding-left: 20px !important;
    padding-right: 20px !important;
    padding-bottom: 0 !important;
    &-row {
      display: flex;
      align-items: center;
      justify-content: flex-start;
      flex-wrap: wrap;
    }
  }

  &-table {
    flex: 1;
    background: white;

    & > * {
      box-sizing: border-box;
    }

    & .query-table-toolbar {
      margin-bottom: 16px;
      overflow: inherit;
      display: flex;
      align-items: center;
      justify-content: flex-start;
      flex-wrap: nowrap;
      gap: 16px;

      &-title {
        flex: 3;
        min-width: 240px;
        text-align: left;

      }

      &-operator {
        flex: 8;
        //min-width: 80%;
        overflow: hidden;

        & .toolbar-scroll-inner{
          overflow-x: auto;
          white-space: nowrap;
          word-break: break-all;
          text-align: right;

          scrollbar-color: #fdfdfd #badaff;
          scrollbar-width:thin;

          &::-webkit-scrollbar-track-piece {
            background: #fdfdfd;
          }

          &::-webkit-scrollbar {
            width: 4px;
            height: 6px;
          }

          &::-webkit-scrollbar-thumb {
            background: #badaff;
            border-radius: 3px;
            -webkit-box-shadow: inset 0 0 3px #fdfdfd;
          }

          &::-webkit-scrollbar-track {
            -webkit-box-shadow: inset 0 0 3px #badaff;
            border-radius: 0;
            background: #fdfdfd;
          }
        }
      }

      &-config {
        flex: 1;
        max-width: 120px;
      }
    }

    & .query-table-batchbar {
      line-height: 44px;
      margin-bottom: 16px;

      &-content {
        width: 100%;
        background: #e6f7ff;
        border: 1px solid #bae7ff;
        border-radius: 2px;
        box-sizing: border-box;
        display: flex;
        align-items: center;
        justify-content: flex-start;

        & > *:last-child {
          margin-left: auto;
        }
      }
    }

    & .column-operator {
      &-split {
        margin: 0 5px;
        color: #d8d8d8;
      }
    }
  }

  &-batchfooter {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 10;
    line-height: 50px;
    background: #ffffff;
    box-shadow: 0 -1px 2px 0 rgba(0, 0, 0, 0.03);
    filter: blur(0);
    text-align: right;
  }


  .no-margin-bottom {
    :deep(.el-form-item) {
      margin-bottom: 0;
    }
  }

  :deep(.el-table) {
    .tree-col-class .cell {
      display: flex;
    }

    .el-loading-parent--relative {
      display: inline-block;
    }

    .el-loading-spinner {
      margin-top: unset;
      top: unset;
    }
  }

  :deep(.el-form-item) {
    .el-form-item--medium .el-form-item__content {
      height: 36px;
    }

    .el-form-item--small .el-form-item__content {
      height: 32px;
    }

    .el-form-item--mini .el-form-item__content {
      height: 28px;
    }
  }

  :deep(.el-input__inner) {
    &.el-date-editor--datetimerange,
    &.el-date-editor--daterange {
      width: 100% !important;
    }
  }

  :deep(.el-select) {
    width: 100% !important;
  }

  :deep(.el-button) {
    &.is-loading:before {
      background-color: transparent;
    }
  }
}
</style>
